package com.project.im.web.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.SecureUtil;
import com.google.common.base.Joiner;
import com.project.im.app.dto.AppClientApplyDTO;
import com.project.im.app.dto.WebUserDetails;
import com.project.im.common.util.SecurityUtils;
import com.project.im.infra.entity.AppClient;
import com.project.im.infra.service.AppClientService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Instant;

@Slf4j
@Service
@RequiredArgsConstructor
public class AppClientWebService {

    private final AppClientService appClientService;

    public void apply(AppClientApplyDTO applyDTO) {
        AppClient appClient = new AppClient();
        appClient.setAppKey(UUID.fastUUID().toString(true));
        appClient.setAppName(applyDTO.getAppName());
        appClient.setAppCategory(applyDTO.getAppCategory());
        appClient.setAppDesc(applyDTO.getAppDesc());
        String appSecret = SecureUtil.sha256(Joiner.on("-").join(appClient.getAppKey(), appClient.getAppCategory(), Instant.now().toEpochMilli()));
        appClient.setAppSecret(appSecret);
        appClient.setUserId(SecurityUtils.getValue(WebUserDetails.class, WebUserDetails::getId));
        appClient.setEnabled(false);
        appClientService.save(appClient);
    }

}
